package cqu.zhaiyixin20215521.huarondao.slice.pintuInitialize;

import cqu.zhaiyixin20215521.huarondao.ResourceTable;
import cqu.zhaiyixin20215521.huarondao.slice.huarondaoPlay.HuaRonDaoPlaySlice;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.media.image.PixelMap;

import java.util.ArrayList;
import java.util.Arrays;

public class PintuInitializeAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent((ComponentContainer) LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_ability_pintu_init, null, false));
        IntentParams intentParams = intent.getParams();
        PixelMap[] pixelMaps = (PixelMap[]) intentParams.getParam("pixelMaps");
        Pintu pintu = new Pintu((Integer) intentParams.getParam("rowCount"), (Integer) intentParams.getParam("colCount"));
        Pintu.Piece[] pieces = new Pintu.Piece[pintu.size() - 1];
        for(int i = 0; i < pintu.size() - 1; ++i) {
            pieces[i] = new Pintu.Piece(i, pixelMaps[i]);
        }
        PixelMap finalPiece = pixelMaps[pintu.size() - 1];
        PixelMap chosenPicture = (PixelMap) intentParams.getParam("picture");
        TableLayout.LayoutConfig pieceLayoutConfig = initPintuGrid(pintu.rowNum, pintu.colNum); //初始化拼图框
        Image[] images = initPieces(pintu, pieces, pieceLayoutConfig.width, pieceLayoutConfig.height); //初始化拼图块
        initSubmitButton(pintu, finalPiece, chosenPicture); //初始化提交按钮
        initRandomlyFillButton(pintu, pieces, images); //初始化随机填充按钮
    }

    public TableLayout.LayoutConfig initPintuGrid(int rowNum, int colNum) {
        TableLayout pintuGrid = findComponentById(ResourceTable.Id_PintuInitAbilityPiecesTable);
        DirectionalLayout frame = findComponentById(ResourceTable.Id_PintuInitAbilityTableFrame);
        ComponentContainer.LayoutConfig config = pintuGrid.getLayoutConfig();
        if(rowNum >= colNum) {
            config.height = frame.getHeight();
            config.width = frame.getHeight() * colNum / rowNum;
        } else {
            config.width = frame.getWidth();
            config.height = frame.getWidth() * rowNum / colNum;
        }
        pintuGrid.setLayoutConfig(config);
        pintuGrid.setRowCount(rowNum);
        pintuGrid.setColumnCount(colNum);
        TableLayout.LayoutConfig pieceLayoutConfig = new TableLayout.LayoutConfig(config.width / colNum, config.height / rowNum);
        for(int i = 0; i < rowNum * colNum; ++i) { //填充空白Image
            pieceLayoutConfig.rowSpec = TableLayout.specification(i / colNum,1);
            pieceLayoutConfig.columnSpec = TableLayout.specification(i % colNum, 1);
            pintuGrid.addComponent(new Image(this), i, pieceLayoutConfig);
        }
        return pieceLayoutConfig;
    }

    public Image[] initPieces(Pintu pintu, Pintu.Piece[] pieces, int width, int height) {
        PositionLayout page = findComponentById(ResourceTable.Id_PintuInitAbilityPage);
        Image[] images = new Image[pintu.size() - 1];
        int baseY = AttrHelper.vp2px(400, this);
        int deltaX = AttrHelper.vp2px(10, this);
        for(int i = 0; i < pintu.size() - 1; ++i) {
            Image image = new Image(this);
            image.setPixelMap(pieces[i].pixelMap);
            image.setScaleMode(Image.ScaleMode.STRETCH);
            page.addComponent(image, width, height);
            image.setPosition(i * deltaX, baseY);
            Image draggedImage = new Image(this);//拖动时显示的图像
            draggedImage.setWidth(width);
            draggedImage.setHeight(height);
            draggedImage.setScaleMode(Image.ScaleMode.STRETCH);
            draggedImage.setAlpha(0.70F);
            image.setLongClickedListener(new imageLongClickedListener(draggedImage));
            image.setOnDragListener(new imageOnDragListener(pintu, draggedImage, pieces[i]));
            images[i] = image;
        }
        return images;
    }

    public class imageLongClickedListener implements Component.LongClickedListener {
        Component.DragFeedbackProvider dragFeedbackProvider;
        public imageLongClickedListener(Image draggedImage) {
            this.dragFeedbackProvider = new Component.DragFeedbackProvider(draggedImage);
        }
        @Override
        public void onLongClicked(Component component) {
            component.setVisibility(Component.INVISIBLE);
            component.startDragAndDrop(null, dragFeedbackProvider);
        }
    }

    public class imageOnDragListener implements Component.OnDragListener {
        Image draggedImage;
        Pintu.Piece piece;
        TableLayout pintuGrid;
        PositionLayout page;
        Pintu pintu;
        int width, height; //拼图块的宽高
        public imageOnDragListener(Pintu pintu, Image draggedImage, Pintu.Piece piece) {
            this.pintu = pintu;
            this.draggedImage = draggedImage;
            this.piece = piece;
            pintuGrid = PintuInitializeAbilitySlice.this.findComponentById(ResourceTable.Id_PintuInitAbilityPiecesTable);
            width = draggedImage.getWidth();
            height = draggedImage.getHeight();
            page = PintuInitializeAbilitySlice.this.findComponentById(ResourceTable.Id_PintuInitAbilityPage);
        }
        @Override
        public boolean onDrag(Component component, DragEvent dragEvent) {
            Image image = (Image) component;
            if (component.getVisibility() == ListComponent.INVISIBLE) {
                draggedImage.setPixelMap(image.getPixelMap());
                int baseX, baseY;
                int row, col, index;
                switch (dragEvent.getAction()) {
                    case DragEvent.DRAG_BEGIN:
                        baseX = pintuGrid.getLocationOnScreen()[0] - width / 2;
                        baseY = pintuGrid.getLocationOnScreen()[1] - height / 2;
                        row = (image.getLocationOnScreen()[1] - baseY) / height; //判断拼图在哪个网格
                        col = (image.getLocationOnScreen()[0] - baseX) / width;
                        index = row * pintu.colNum + col;
                        if (pintu.removeIfEquals(row, col, piece) != null) { //从拼图框里被拖动
                            pintuGrid.removeComponentAt(index);
                            pintuGrid.addComponent(new Image(PintuInitializeAbilitySlice.this), index, image.getLayoutConfig());
                            page.addComponent(image);
                        }
                        break;
                    case DragEvent.DRAG_FINISH:
                        baseX = pintuGrid.getLocationOnScreen()[0] - width / 2;
                        baseY = pintuGrid.getLocationOnScreen()[1] - height / 2;
                        row = (draggedImage.getLocationOnScreen()[1] - baseY) / height;
                        col = (draggedImage.getLocationOnScreen()[0] - baseX) / width;
                        index = row * pintu.colNum + col;
                        if (pintu.insert(piece, row, col)) { //进入拼图框
                            page.removeComponent(image);
                            Image nullImage = (Image) pintuGrid.getComponentAt(index);
                            pintuGrid.removeComponentAt(index);
                            pintuGrid.addComponent(image, index, nullImage.getLayoutConfig());
                        } else { //在框外
                            image.setPosition((int) draggedImage.getContentPositionX(), (int) draggedImage.getContentPositionY());
                        }
                        image.setVisibility(Component.VISIBLE);
                        break;
                }
            }
            return true;
        }
    }

    private void initSubmitButton(Pintu pintu, PixelMap finalPiece, PixelMap chosenPicture) {
        Button submitButton = findComponentById(ResourceTable.Id_PintuInitAbilitySubmitButton);
        submitButton.setClickedListener(component -> {
            if(pintu.getCount() + 1 == pintu.size()) { //拼图数够了
                IntentParams intentParams = new IntentParams();
                intentParams.setParam("pintu", pintu);
                intentParams.setParam("finalPiece", finalPiece);
                intentParams.setParam("chosenPicture", chosenPicture);
                Intent intent = new Intent();
                intent.setParams(intentParams);
                present(new HuaRonDaoPlaySlice(), intent);
            } else {
                new ToastDialog(this)
                        .setText("请拼完所有拼图块！")
                        .show();
            }
        });
    }

    private void initRandomlyFillButton(Pintu pintu, Pintu.Piece[] pieces, Image[] images) {
        Button randomlyFillButton = findComponentById(ResourceTable.Id_PintuInitAbilityRandomlyFillButton);
        PositionLayout page = findComponentById(ResourceTable.Id_PintuInitAbilityPage);
        TableLayout pintuGrid = findComponentById(ResourceTable.Id_PintuInitAbilityPiecesTable);
        RandomlyFill randomlyFill = new RandomlyFill(pintu.rowNum, pintu.colNum);
        randomlyFillButton.setClickedListener(component -> {
            randomlyFill.shuffle(10000);
            int[] permute = randomlyFill.pieces;
            pintu.clearAll();
            for(int i = 0; i < permute.length; ++i) { //清空拼图网格
                Image removedImage = (Image) pintuGrid.getComponentAt(i);
                pintuGrid.removeComponentAt(i);
                pintuGrid.addComponent(new Image(this), i, removedImage.getLayoutConfig());
            }
            for(int i = 0; i < permute.length; ++i) {
                if(permute[i] != permute.length - 1) {
                    pintu.insert(pieces[permute[i]], i);
                    Image removedImage = (Image) pintuGrid.getComponentAt(i);
                    pintuGrid.removeComponentAt(i);
                    page.removeComponent(images[permute[i]]);
                    pintuGrid.addComponent(images[permute[i]], i, removedImage.getLayoutConfig());
                }
            }
        });
    }

}
